﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
using System.Collections;
using LHS.Core.TableInfo;
using MS.Core.Constants.Objects;
using System.IO;

namespace LHS.Win
{
    public partial class frmCapNhatNhanVien : Form
    {  // Methods
        #region Variable
        LHS.Core.Authority.AuthorityController objController = new LHS.Core.Authority.AuthorityController();
        private Bitmap MyImage;
        private bool blnChangeImage = false; //bien kiem tra xem user co change image cho chữ ký hay không?
        #endregion

        public frmCapNhatNhanVien()
        {
            this.InitializeComponent();
        }

        #region Button Event
        private void btThem_Click(object sender, EventArgs e)
        {
            if (this.tbFullName.Text == "")
            {
                MessageBox.Show("Vui lòng tên nhân viên!", "Lỗi nhập", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            else if (this.tbAge.Text == "")
            {
                MessageBox.Show("Vui lòng nhập ngày sinh!", "Lỗi nhập", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            else if ((Convert.ToInt64(this.tbAge.Text.ToString()) < 0L) && (Convert.ToInt64(this.tbAge.Text.ToString()) > 120L))
            {
                MessageBox.Show("Ngày sinh không hợp lệ!", "Lỗi nhập", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            else if (this.cbChucVu.Text == "")
            {
                MessageBox.Show("Vui lòng chọn chức vụ!", "Lỗi nhập", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            else if (this.tbChuyenMon.Text == "")
            {
                MessageBox.Show("Vui lòng nhập chuyên môn!", "Lỗi nhập", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            else if (this.tbAddress.Text == "")
            {
                MessageBox.Show("Vui lòng nhập địa chỉ!", "Lỗi nhập", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            else if ((this.tbPhone.Text.Length > 0) && !this.IsNumber(this.tbPhone.Text.ToString()))
            {
                MessageBox.Show("Số điện thoại không hợp lệ", "Lỗi nhập", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            else if ((this.tbDiDong.Text.Length > 0) && !this.IsNumber(this.tbDiDong.Text.ToString()))
            {
                MessageBox.Show("Số điện thoại di động không hợp lệ", "Lỗi nhập", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            else if ((this.tbEmail.Text.Length > 0) && !Regex.IsMatch(this.tbEmail.Text, @"^([\w-]+\.)*?[\w-]+@[\w-]+\.([\w-]+\.)*?[\w]+$"))
            {
                MessageBox.Show("Địa chỉ E-Mail không hợp lệ!", "Lỗi nhập", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            else
            {
                string str;
                if (this.rbMale.Checked)
                {
                    str = "Nam";
                }
                else
                {
                    str = "Nữ";
                }
                try
                {

                    DataTable dtEmployee = InfoEmployees.GetStructure();
                   
                    dtEmployee.Columns.Remove(InfoEmployees.EMPISN);
                    DataRow dr = dtEmployee.NewRow();
                    dr[InfoEmployees.EMPID] = this.tbID.Text;
                    dr[InfoEmployees.EMPNAME] = this.tbFullName.Text;
                    dr[InfoEmployees.EMPBIRTHDATE] = this.dtpBirthDay.Value;
                    dr[InfoEmployees.EMPAGE] = this.tbAge.Text;
                    dr[InfoEmployees.EMPSEX] = str;
                    dr[InfoEmployees.EMPPOSITION] = this.cbChucVu.Text;
                    dr[InfoEmployees.EMPSPECIALIZE] = this.tbChuyenMon.Text;
                    dr[InfoEmployees.EMPADDRESS] = this.tbAddress.Text;
                    dr[InfoEmployees.EMPTEL] = this.tbPhone.Text;
                    dr[InfoEmployees.EMPMOBILE] = this.tbDiDong.Text;
                    dr[InfoEmployees.EMPEMAIL] = this.tbEmail.Text;

                    ///thumbnail chữ ký rồi lưu vào image vào DB
                    ///edit by thaoht 20090603
                    if (blnChangeImage == true)
                    {
                        if (picSignature.Image == null)
                        {
                            dr[InfoEmployees.EMPSIGNATUREIMAGE] = DBNull.Value;
                        }
                        else
                        {
                            Image.GetThumbnailImageAbort abort = new Image.GetThumbnailImageAbort(this.ThumbnailCallback);
                            Image img = picSignature.Image.GetThumbnailImage(133, 50, abort, System.IntPtr.Zero);
                            MemoryStream stream = new MemoryStream();
                            img.Save(stream, this.picSignature.Image.RawFormat);
                            byte[] buffer = stream.GetBuffer();
                            stream.Close();

                            dr[InfoEmployees.EMPSIGNATUREIMAGE] = buffer; //phan them moi 20090603
                        }
                    }
                    else
                    {
                        dtEmployee.Columns.Remove(InfoEmployees.EMPSIGNATUREIMAGE); // khong cập nhật field chữ ký
                    }
                    //end edit phan them moi

                    dtEmployee.Rows.Add(dr);
                    objController.UpdateRow(dr, new string[] { InfoEmployees.EMPID });

                    this.frmCapNhatNhanVien_Load(sender, e);
                    MessageBox.Show("Cập nhật thành công!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.tbID.Text = "";
                    this.tbFullName.Text = "";
                    this.tbAge.Text = "";
                    this.tbChuyenMon.Text = "";
                    this.tbAddress.Text = "";
                    this.tbPhone.Text = "";
                    this.tbDiDong.Text = "";
                    this.tbEmail.Text = "";
                    this.picSignature.Image = null; //edit 20090603 by thaoht
                    cbChucVu.EditValue = 0; //edit here 20091025
                    this.btThem.Enabled = false;
                    this.dataGrid1.Visible = true;
                    this.dataGrid2.Visible = false;
                    blnChangeImage = false; // set thong tin cap nhat image chữ ký bằng false; edit by 20090603
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }
            }
        }

        private void btThoat_Click(object sender, EventArgs e)
        {
            base.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.dataGrid1.Visible = true;
            this.dataGrid2.Visible = false;
            if (this.rbAll.Checked)
            {
                this.frmCapNhatNhanVien_Load(sender, e);
            }
            else if (this.tbKeySearch.Text == "")
            {
                MessageBox.Show("Vui lòng nhập từ khóa tìm kiếm!", "Lỗi tìm kiếm", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            else
            {
               
                if (this.rbFullName.Checked)
                {
                    List<ExpressionObject> param = new List<ExpressionObject>();
                    param.Add(new ExpressionObject(InfoEmployees.EMPNAME, tbKeySearch.Text.Trim(), ExpressionObject.eSelectOperator.LikeAll));
                    DataTable dtEmployee = objController.GetData(InfoEmployees.TABLENAME,param);

                    if (dtEmployee.Rows.Count == 0)
                    {
                        MessageBox.Show("Không tìm thấy nhân viên: " + this.tbKeySearch.Text.Trim(), "", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    else
                    {
                        DataSet dsEmployee = new DataSet();
                        dsEmployee.Tables.Add(dtEmployee);
                        this.dataGrid1.Visible = false;
                        this.dataGrid2.Visible = true;
                        this.dataGrid2.CaptionText = "Danh Sách Nhân Viên";
                        this.dataGrid2.DataSource = dsEmployee;
                        this.dataGrid2.SetDataBinding(dsEmployee, InfoEmployees.TABLENAME);
                        this.dataGrid2.TableStyles.Clear();
                        this.loadDataGrid();
                        this.dataGrid2.TableStyles.Add(this.TblStyle);
                        this.dataGrid2.ReadOnly = true;
                        ArrayList list = new ArrayList();
                        for (int i = 0; i < dtEmployee.Rows.Count; i++)
                        {
                            foreach (string str in dtEmployee.Rows[i][3].ToString().Split(new char[] { '/' }))
                            {
                                list.Add(str);
                            }
                            dtEmployee.Rows[i][10] = list[1].ToString() + "/" + list[0].ToString() + "/" + list[2].ToString().Remove(4, list[2].ToString().Length - 4);
                            list.Clear();
                        }
                        return;
                    }
                }
                if (this.rbID.Checked)
                {
                    List<ExpressionObject> param = new List<ExpressionObject>();
                    param.Add(new ExpressionObject(InfoEmployees.EMPID, tbKeySearch.Text.Trim()));
                    DataTable dtEmployee = objController.GetData(InfoEmployees.TABLENAME,param);

                    if (dtEmployee.Rows.Count == 0)
                    {
                        MessageBox.Show("Không tìm thấy nhân viên: " + this.tbKeySearch.Text.Trim(), "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                    else
                    {
                        DataSet dsEmployee = new DataSet();
                        dsEmployee.Tables.Add(dtEmployee);
                        this.dataGrid1.Visible = false;
                        this.dataGrid2.Visible = true;
                        this.dataGrid2.CaptionText = "Danh Sách Nhân Viên";
                        this.dataGrid2.DataSource = dsEmployee;
                        this.dataGrid2.SetDataBinding(dsEmployee, InfoEmployees.TABLENAME);
                        this.dataGrid2.TableStyles.Clear();
                        this.loadDataGrid();
                        this.dataGrid2.TableStyles.Add(this.TblStyle);
                        this.dataGrid2.ReadOnly = true;
                        ArrayList list2 = new ArrayList();
                        for (int j = 0; j < dtEmployee.Rows.Count; j++)
                        {
                            foreach (string str2 in dtEmployee.Rows[j][3].ToString().Split(new char[] { '/' }))
                            {
                                list2.Add(str2);
                            }
                            dtEmployee.Rows[j][10] = list2[1].ToString() + "/" + list2[0].ToString() + "/" + list2[2].ToString().Remove(4, list2[2].ToString().Length - 4);
                            list2.Clear();
                        }
                    }
                }
            }
        }
        #endregion

        #region Datagrid
        private void dataGrid1_MouseUp(object sender, MouseEventArgs e)
        {
            if ((this.dataGrid1.DataSource != null) && (e.Button == MouseButtons.Left))
            {
                DataGrid.HitTestInfo info = this.dataGrid1.HitTest(e.X, e.Y);
                if (info.Type == DataGrid.HitTestType.RowHeader)
                {
                    this.dataGrid1.Select(info.Row);
                    try
                    {
                        DataSet dataSource = (DataSet)this.dataGrid1.DataSource;
                        if (dataSource != null)
                        {
                            string strEMPID = dataSource.Tables[InfoEmployees.TABLENAME].Rows[info.Row][InfoEmployees.EMPID].ToString();
                            chooseEmployee(strEMPID);
                        }
                    }
                    catch
                    {
                        MessageBox.Show("Chưa có dữ liệu", "Chưa Có Dữ Liệu", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                }
            }
        }

        /// <summary>
        /// hàm dùng để chọn dữ liệu Employee đang được focus trên lưới
        /// </summary>
        /// <param name="strEMPID"></param>
        private void chooseEmployee(string strEMPID)
        {
            List<ExpressionObject> param = new List<ExpressionObject>();
            param.Add(new ExpressionObject(InfoEmployees.EMPID, strEMPID));
            DataTable dtEmployee = objController.GetData(InfoEmployees.TABLENAME, param);
            if (dtEmployee.Rows.Count > 0)
            {
                DataRow dr = dtEmployee.Rows[0];
                this.tbID.Text = strEMPID;
                this.tbFullName.Text = dr[InfoEmployees.EMPNAME].ToString();
                if (string.IsNullOrEmpty(dr[InfoEmployees.EMPBIRTHDATE].ToString()))
                    this.dtpBirthDay.ResetText();
                else
                    this.dtpBirthDay.Value = DateTime.Parse( dr[InfoEmployees.EMPBIRTHDATE].ToString()); //kiem tra lai khi test
                this.tbAge.Text = dr[InfoEmployees.EMPAGE].ToString();
                if (dr[InfoEmployees.EMPSEX].ToString() == "Nam")
                {
                    this.rbMale.Checked = true;
                }
                else
                {
                    this.rbFemale.Checked = true;
                }
                this.tbAddress.Text = dr[InfoEmployees.EMPADDRESS].ToString();
                this.tbPhone.Text = dr[InfoEmployees.EMPTEL].ToString();
                this.tbDiDong.Text = dr[InfoEmployees.EMPMOBILE].ToString();
                this.tbChuyenMon.Text = dr[InfoEmployees.EMPSPECIALIZE].ToString();
                this.tbEmail.Text = dr[InfoEmployees.EMPEMAIL].ToString();

                ///phan moi them cho phần chữ ký
                ///edit by thaoht 20090603
                if (dr[InfoEmployees.EMPSIGNATUREIMAGE] is byte[])
                {
                    byte[] buffer = (byte[])dr[InfoEmployees.EMPSIGNATUREIMAGE];
                    MemoryStream stream = new MemoryStream(buffer);
                    this.picSignature.Image = Image.FromStream(stream);
                    stream.Close();
                    stream.Flush();
                }
                else
                {
                    this.picSignature.Image = null;
                }
                //end edit phan moi them
                //edit here 20091025
                if (dr[InfoEmployees.EMPPOSITION].ToString() == "Trưởng Phòng Khám")
                {
                   // this.cbChucVu.SelectedIndex = 0; //edit
                }
                else if (dr[InfoEmployees.EMPPOSITION].ToString() == "Bác Sĩ")
                {
                    // this.cbChucVu.SelectedIndex = 1;//edit
                }
                else if (dr[InfoEmployees.EMPPOSITION].ToString() == "Y Tá")
                {
                    // this.cbChucVu.SelectedIndex = 2;//edit
                }
                else
                {
                    // this.cbChucVu.SelectedIndex = 3;//edit
                }
            }
            this.btThem.Enabled = true; //nên xem lại khi test--> đưa ra lý do tại sao thêm dòng này
        }

        private void dataGrid2_MouseUp(object sender, MouseEventArgs e)
        {
            if ((this.dataGrid2.DataSource != null) && (e.Button == MouseButtons.Left))
            {
                DataGrid.HitTestInfo info = this.dataGrid2.HitTest(e.X, e.Y);
                if (info.Type == DataGrid.HitTestType.RowHeader)
                {
                    this.dataGrid2.Select(info.Row);
                    DataSet dataSource = (DataSet)this.dataGrid2.DataSource;
                    if (dataSource != null)
                    {
                        string strEMPID = dataSource.Tables[InfoEmployees.TABLENAME].Rows[info.Row][InfoEmployees.EMPID].ToString();
                        chooseEmployee(strEMPID);
                    }
                }
            }
        }

        public void loadDataGrid()
        {
            this.TblStyle = new DataGridTableStyle();
            this.TblStyle.MappingName = InfoEmployees.TABLENAME;
            this.TblStyle.RowHeaderWidth = 40;
            this.TblStyle.AlternatingBackColor = Color.AliceBlue;
            this.TblStyle.HeaderForeColor = Color.Maroon;
            this.TblStyle.GridLineColor = Color.CornflowerBlue;
            this.TblStyle.AllowSorting = false;

            DataGridTextBoxColumn column = new DataGridTextBoxColumn();
            column.MappingName = InfoEmployees.EMPID;
            column.HeaderText = "Số ID";
            column.Width = 60;
            column.NullText = string.Empty;
            this.TblStyle.GridColumnStyles.Add(column);

            DataGridTextBoxColumn column2 = new DataGridTextBoxColumn();
            column2.MappingName = InfoEmployees.EMPNAME;
            column2.HeaderText = "Họ tên";
            column2.Width = 150;
            column2.NullText = string.Empty;
            this.TblStyle.GridColumnStyles.Add(column2);

            DataGridTextBoxColumn column3 = new DataGridTextBoxColumn();
            column3.MappingName = InfoEmployees.EMPBIRTHDATE;
            column3.HeaderText = "Ngày Sinh";
            column3.Width = 0;
            column3.NullText = string.Empty;
            this.TblStyle.GridColumnStyles.Add(column3);

            DataGridTextBoxColumn column4 = new DataGridTextBoxColumn();
            column4.MappingName = InfoEmployees.EMPMOBILE;
            column4.HeaderText = "Mobile";
            column4.Width = 80;
            column4.NullText = string.Empty;
            this.TblStyle.GridColumnStyles.Add(column4);

            DataGridTextBoxColumn column5 = new DataGridTextBoxColumn();
            column5.MappingName = InfoEmployees.EMPPOSITION;
            column5.HeaderText = "Loại Nhân Viên";
            column5.Width = 130;
            column5.NullText = string.Empty;
            this.TblStyle.GridColumnStyles.Add(column5);

            DataGridTextBoxColumn column6 = new DataGridTextBoxColumn();
            column6.MappingName = InfoEmployees.EMPSPECIALIZE;
            column6.HeaderText = "Chuyên Môn";
            column6.Width = 130;
            column6.NullText = string.Empty;
            this.TblStyle.GridColumnStyles.Add(column6);

            DataGridTextBoxColumn column7 = new DataGridTextBoxColumn();
            column7.MappingName = InfoEmployees.EMPADDRESS;
            column7.HeaderText = "Địa chỉ";
            column7.Width = 180;
            column7.NullText = string.Empty;
            this.TblStyle.GridColumnStyles.Add(column7);

            DataGridTextBoxColumn column8 = new DataGridTextBoxColumn();
            column8.MappingName = InfoEmployees.EMPTEL;
            column8.HeaderText = "Điện Thoại";
            column8.Width = 80;
            column8.NullText = string.Empty;
            this.TblStyle.GridColumnStyles.Add(column8);

            DataGridTextBoxColumn column9 = new DataGridTextBoxColumn();
            column9.MappingName = InfoEmployees.EMPEMAIL;
            column9.HeaderText = "E-Mail";
            column9.Width = 180;
            column9.NullText = string.Empty;

            this.TblStyle.GridColumnStyles.Add(column9);
        }

        #endregion Datagrid

        private void frmCapNhatNhanVien_Load(object sender, EventArgs e)
        {
            LoadCboData();

            DataTable dtEmployees = objController.GetData(InfoEmployees.TABLENAME);
            if (dtEmployees.Rows.Count == 0)
            {
                MessageBox.Show("Hiện tại chưa có nhân viên nào tồn tại!\nVui lòng nhập nhân viên mới.", "Không tìm thấy nhân viên", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                this.dataGrid1.Enabled = false;
            }
            else
            {
                DataSet dsEmployee = new DataSet();
                dsEmployee.Tables.Add(dtEmployees);
                this.dataGrid1.Enabled = true;
                this.dataGrid1.CaptionText = "Danh sách Nhân Viên";
                this.dataGrid1.DataSource = dsEmployee;
                this.dataGrid1.SetDataBinding(dsEmployee, InfoEmployees.TABLENAME);
                this.dataGrid1.TableStyles.Clear();
                this.loadDataGrid();
                this.dataGrid1.TableStyles.Add(this.TblStyle);
                this.dataGrid1.ReadOnly = true;
                ArrayList list = new ArrayList();
                for (int i = 0; i < dtEmployees.Rows.Count; i++)
                {
                    foreach (string str in dtEmployees.Rows[i][3].ToString().Split(new char[] { '/' }))
                    {
                        list.Add(str);
                    }
                    dtEmployees.Rows[i][10] = list[1].ToString() + "/" + list[0].ToString() + "/" + list[2].ToString().Remove(4, list[2].ToString().Length - 4);
                    list.Clear();
                }
            }
        }

        /// <summary>
        /// Load combobox
        /// </summary>
        private void LoadCboData()
        {
            ///load chuc vu
            DataTable dtRole = objController.GetData(InfoRoles.TABLENAME);
            cbChucVu.Properties.DataSource = dtRole;
            cbChucVu.Properties.DisplayMember = InfoRoles.ROLNAME;
            cbChucVu.Properties.ValueMember = InfoRoles.ROLISN;
        }

        #region Utility
        private bool IsNumber(string Number)
        {
            try
            {
                long.Parse(Number);
                return true;
            }
            catch
            {
                return false;
            }
        }

        private void dtpBirthDay_Leave(object sender, EventArgs e)
        {
            this.tbAge.Text = (Convert.ToInt32(DateTime.Now.Year) - Convert.ToInt32(dtpBirthDay.Value.Year)).ToString();
        }

        private void tbDiDong_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar) && (e.KeyChar != '\b'))
            {
                e.Handled = true;
            }
        }

        private void tbKeySearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                this.button1_Click(sender, e);
            }
        }

        private void tbPhone_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar) && (e.KeyChar != '\b'))
            {
                e.Handled = true;
            }
        }

        #endregion 

        #region Signature
        /// <summary>
        /// phần cho chọn thêm chữ ký
        /// edit by thaoht 20090603
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "JPEG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif|Bitmap Files (*.bmp)|*.bmp";
            dialog.FilterIndex = 1;
            dialog.RestoreDirectory = true;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                if (this.MyImage != null)
                {
                    this.MyImage.Dispose();
                }
                this.MyImage = new Bitmap(dialog.FileName);
                this.picSignature.Image = this.MyImage;
                this.MyImage = null;
                blnChangeImage = true; //sau khi da chon image để change từ nút browse thì biến blnChangeImage set = true
            }
        }

        public bool ThumbnailCallback()
        {
            return false;
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.picSignature.Image = null;
            blnChangeImage = true; //sau khi da chon image để change từ nút browse thì biến blnChangeImage set = true
        }
        #endregion

    }
}